<?php

namespace app\system\service;

use app\model\Stock;
use app\model\SystemOperLog;
use app\traits\ServiceTrait;
use app\traits\UserTrait;
use think\facade\Db;
use think\helper\Arr;

class LogsService
{
    use ServiceTrait;
    use UserTrait;
    public function getList(?array $params = null, $field = ['*'])
    {
        $query = SystemOperLog::order(['id' => 'desc']);
        if ($username = Arr::get($params, 'username')) {
            $query->where(['username' => $username]);
        }
        if ($ip = Arr::get($params, 'ip')) {
            $query->where(['ip' => $ip]);
        }
        if ($createdAt = Arr::get($params, 'created_at')) {
            $query->whereBetween('created_at', $createdAt);
        }
        if (Arr::get($params, 'is_self')) {
            $query->where('created_by', '=', $this->getUid());
        }
        $pagination = $query->field($field)
            ->paginate([
                'list_rows' => Arr::get($params, $this->listRowsName('system'), 15),
                'var_page' => 'page',
            ])->each(function($item) {
                $stockIds = Db::name('system_stock_user')->where(['user_id' => $item->created_by])->column('stock_id');
                $item->stocks = Stock::where(['id' => $stockIds])->field('id,name')->select();
            });
        return pagination($pagination);
    }
}